package com.rabbitmq.work;

import com.rabbitmq.RabbitMqConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接
        Connection connection = RabbitMqConnectionUtil.getConnection();
        //创建频道
        Channel channel = connection.createChannel();
        //创建队列,创建消费者,并设置消息处理
        channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null);
        //监听消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println("<-=-=-=-=-=-=-=-=-=-=-=-=-=-消费者1开始=-=-=-=-=-=-=-=-=-=-=-=-=-=->");
                //路由key
                System.out.println("路由key为：" + envelope.getRoutingKey());
                //交换机
                System.out.println("交换机为：" + envelope.getExchange());
                //消息ID
                System.out.println("消息的ID：" + envelope.getDeliveryTag());
                //收到的消息
                System.out.println("接收到的消息为：" + new String(body, "UTF-8"));
                System.out.println("<-=-=-=-=-=-=-=-=-=-=-=-=-=-消费者1结束=-=-=-=-=-=-=-=-=-=-=-=-=-=->");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        channel.basicConsume(Producer.QUEUE_NAME, true, consumer);
    }
}
